//
//  GluSetVc.m
//  CareRingApp
//
//  Created  on 2025/2/19.
//
    

#import "GluSetVc.h"
#import <Masonry/Masonry.h>
#import <QMUIKit/QMUIKit.h>
#import "ConfigModel.h"
#import "NormalSetCell.h"
#import "GluSegVc.h"
#import "GluNetObj.h"
//#import "DeviceCenter.h"
#import "NSDate+HMTools.h"
#import "NSString+Check.h"
#import "UIViewController+Custom.h"


#import "NSString+Check.h"

typedef NS_ENUM(NSUInteger, GLU_SET) {
    GLU_SET_family_history,     //Family history of diabetes
    GLU_SET_high_cholesterol,   //Family history of high cholesterol
    
    GLU_SET_AB_glu_asses,       // About Glycemic Risk Assessment
    GLU_SET_AB_Diabetes_asses,  // About Diabetes Risk Assessment
};

@interface GluSetVc () <UITableViewDelegate, UITableViewDataSource>

@property(strong, nonatomic)UITableView *tableView;
@property(strong, nonatomic)UISwitch *diabetesHisSwitch, *highCholesterolSwitch;
@property(strong, nonatomic)QMUIButton *sureBtn;
@property(strong, nonatomic)NSMutableArray<NSArray<NSNumber *> * > *dataArray;

@property(assign, nonatomic)BOOL family_diabetes_history, high_cholesterol;
@property(strong, nonatomic)NSString *glu_ltk; // 血糖请求令牌
@property(strong, nonatomic)NSNumber *glu_lease; // 血糖令牌过期时间戳

@end

@implementation GluSetVc

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WEAK_SELF
    [self customNavStyleNormal:@"Settings" BackBlk:^{
        STRONG_SELF
        [strongSelf.navigationController popViewControllerAnimated:YES];
    }];
    
    [self initUI];
    
    self.dataArray = [NSMutableArray new];
    NSArray<NSNumber *> * section_1 = @[
        @(GLU_SET_family_history),     //家族糖尿病史
        @(GLU_SET_high_cholesterol),   //家族高胆固醇病史
                                        
                                     
    ];
    
    [self.dataArray addObject:section_1];

    [self.tableView reloadData];
}

-(void)initUI
{
    
    self.highCholesterolSwitch.on = NO;
    self.diabetesHisSwitch.on = NO;

    [self.view addSubview:self.tableView];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.leading.equalTo(self.view).offset(VC_ITEM_MARGIN_HOR);
        make.trailing.equalTo(self.view).inset(VC_ITEM_MARGIN_HOR);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);

    }];
    
}

// 糖尿病史开关
-(void)diabetesHis:(UISwitch *)swh
{
    swh.enabled = NO;
    BOOL isOn = swh.isOn;

    self.family_diabetes_history = isOn;

}

-(void)netReq:(void(^)(BOOL succ))cmp {
    
    NSUInteger age = 37;    // Please adjust according to the actual user data
    BOOL isMale = YES;      // Please adjust according to the actual user data
    NSUInteger weight = 67; // Please adjust according to the actual user data
    NSUInteger height = 175; // Please adjust according to the actual user data
    BOOL familyHistory = self.family_diabetes_history;
    BOOL highCholesterol = self.high_cholesterol;
    
    NSString *sn = CARingSDK.instance.currentDevice.snString;
    NSString *mac = CARingSDK.instance.currentDevice.macAddress;
    
    WEAK_SELF
    // 网络请求
    [GluNetObj gluRegPsn:HOSTNAME SN:sn Age:age Gender:isMale Weight:weight Height:height FamilyHistory:familyHistory
         HighCholesterol:highCholesterol Key:CARingSDK.instance.netKey MacAddr:mac Secret:CARingSDK.instance.netSecret AndComplated:^(NSHTTPURLResponse * _Nullable httpResp, NSDictionary * _Nullable content, NSNumber * _Nullable state , NSNumber * _Nullable lease, NSString *ltk)
     {
        if (state && state.intValue == 0) {
            self.glu_ltk = ltk;
            self.glu_lease = lease;
            if (cmp) {
                cmp(YES);
            }
            
        } else {
            self.glu_ltk = nil;
            self.glu_lease = nil;
            // 异常处理
            if (state.intValue == 1 || state.intValue == 2) {
                [LTPHud.Instance hideHud];
                [self showAlertWarningWithTitle:@"Tips" Msg:@"Your ring does not currently support the blood glucose assessment function. This function requires an additional fee. Please contact customer service." btnOk:@"Sure" OkBLk:^{
                    
                    STRONG_SELF
                    
                    
                } CancelBtn:nil CancelBlk:nil Compelete:nil];
                
            }

            if (httpResp.statusCode != 200) {
                [LTPHud.Instance showText:@"Please make sure the network connection is normal and try again!" Lasting:2];
            }
            
            if (cmp) {
                cmp(NO);
            }
        }
        
    } AndServerNil:^{
        
    }];
}

// 高胆固醇史开关
-(void)highCholesterolHis:(UISwitch *)swh
{
    swh.enabled = NO;
    BOOL isOn = swh.isOn;
    self.high_cholesterol = isOn;
    
    

}

-(void)sure:(QMUIButton *)btn
{

    
    [LTPHud.Instance showHudLasting:30];
    WEAK_SELF
    [self netReq:^(BOOL succ) {
        STRONG_SELF
        [LTPHud.Instance hideHud];
        if (succ) {
            GluSegVc *vc = [[GluSegVc alloc]init];
            vc.glu_ltk = self.glu_ltk;
            vc.glu_lease = self.glu_lease;
            vc.hidesBottomBarWhenPushed = YES;
            [strongSelf.navigationController pushViewController:vc animated:YES];
        }
    }];
 
    
}

#pragma mark -- tableview

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.dataArray[section].count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 44.0f;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
 
    return 35;
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
  
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
 
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
  
    return nil;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NormalSetCell *cell = [[NormalSetCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NormalSetCell"];
    
    if (self.dataArray[indexPath.section].count-1 == indexPath.row) {
        // section最后一行
        [cell removeSepLine];
    } else {
        [cell addSepLine];

    }
    cell.textLabel.font = [UIFont systemFontOfSize:17.f];
    
    int tag = self.dataArray[indexPath.section][indexPath.row].intValue;
    switch (tag) {
        case GLU_SET_family_history:    //家族糖尿病史
        {
            [cell removeArrow];
            cell.textLabel.text = @"Family history of diabetes";
            
            [self.diabetesHisSwitch removeFromSuperview];
            [cell.contentView addSubview:self.diabetesHisSwitch];
            [self.diabetesHisSwitch mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(self.diabetesHisSwitch.superview.mas_centerY);
                make.trailing.equalTo(self.diabetesHisSwitch.superview.mas_trailing).inset(15);
            }];
//            self.notifySwitch.on = self.isNotifyAuth.boolValue;
//            cell.textLabel.textColor = UIColor.whiteColor;
            cell.rightLabel.text = nil;
            
        }
            break;
        case GLU_SET_high_cholesterol:   //家族高胆固醇病史
        {
            [cell removeArrow];

            cell.textLabel.text = @"History of high cholesterol";
            [self.highCholesterolSwitch removeFromSuperview];
            [cell.contentView addSubview:self.highCholesterolSwitch];
            [self.highCholesterolSwitch mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(self.highCholesterolSwitch.superview.mas_centerY);
                make.trailing.equalTo(self.highCholesterolSwitch.superview.mas_trailing).inset(15);
            }];
//            self.notifySwitch.on = self.isNotifyAuth.boolValue;
//            cell.textLabel.textColor = UIColor.whiteColor;
            cell.rightLabel.text = nil;
        }
            break;
        case GLU_SET_AB_glu_asses:       // 关于血糖风险评估
        {
            [cell addArrow];

       
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.adjustsFontSizeToFitWidth = YES;
        }
            break;
        case GLU_SET_AB_Diabetes_asses:  // 关于糖尿病风险评估
        {
            [cell addArrow];

            cell.textLabel.numberOfLines = 0;
            cell.textLabel.adjustsFontSizeToFitWidth = YES;
        }
            break;
        default:
            break;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
}







-(UISwitch *)diabetesHisSwitch
{
    if (!_diabetesHisSwitch) {
        _diabetesHisSwitch = [[UISwitch alloc]init];
        [_diabetesHisSwitch addTarget:self action:@selector(diabetesHis:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _diabetesHisSwitch;
}
-(UISwitch *)highCholesterolSwitch
{
    if (!_highCholesterolSwitch) {
        _highCholesterolSwitch = [[UISwitch alloc]init];
        [_highCholesterolSwitch addTarget:self action:@selector(highCholesterolHis:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _highCholesterolSwitch;
}

-(QMUIButton *)sureBtn
{
    if (!_sureBtn) {
        _sureBtn = [[QMUIButton alloc]init];
        [_sureBtn addTarget:self action:@selector(sure:) forControlEvents:UIControlEventTouchUpInside];

        //
        [_sureBtn setTitle:@"Go Mesaure" forState:UIControlStateNormal];

        _sureBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        _sureBtn.backgroundColor = UIColor.blueColor;
        [_sureBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    }
    
    return _sureBtn;
}
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = ^{
            
            UIView *footView = [UIView new];
            footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 110);
            [footView addSubview:self.sureBtn];
            [self.sureBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.sureBtn.superview.mas_centerX);
                make.height.equalTo(@50);
                make.width.equalTo(self.sureBtn.superview.mas_width).multipliedBy(3/4.0);
                make.bottom.equalTo(self.sureBtn.superview.mas_bottom).inset(3);
            }];
            
            return footView;
            
        }();
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
//        _tableView.scrollEnabled = NO;
        [_tableView registerClass:[NormalSetCell class] forCellReuseIdentifier:NSStringFromClass([NormalSetCell class])];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0.0f;
        }
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
    }
    
    return _tableView;
}

@end
